package org.common.utils;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import org.objective.base.annotations.ColumnMapping;

/**
 *
 * @author gus
 */
public class AnnotationUtils
{
    public static <T extends Annotation> T getAnnotation(Class clazz, Class annotationClass)
    {
        if (!clazz.isAnnotationPresent(annotationClass))
        {
            throw new IllegalArgumentException("not supported class");
        }

        return (T) clazz.getAnnotation(annotationClass);
    }

    public static Map<String, PropertyDescriptor> getFieldMappings(Class clazz) throws Exception
    {
        Map<String, PropertyDescriptor> fields = new HashMap<String, PropertyDescriptor>();
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);

        Map<String, PropertyDescriptor> hashDescriptiors = new HashMap<String, PropertyDescriptor>();
        for (PropertyDescriptor desc : beanInfo.getPropertyDescriptors())
        {
            hashDescriptiors.put(desc.getName(), desc);
        }

        PropertyDescriptor descriptor = null;
        for (Field field : clazz.getDeclaredFields())
        {
            if (field.isAnnotationPresent(ColumnMapping.class))
            {
                ColumnMapping annotation = field.getAnnotation(ColumnMapping.class);
                descriptor = hashDescriptiors.get(field.getName());
                if (descriptor != null)
                {
                    fields.put(annotation.name(), descriptor);
                }
            }
        }
        return fields;
    }
}
